// The reason for adding/subtracting 1 is to allow us to test if the health is actually 0 or if it hasn't been sent yet.
// If it hasn't been sent, the health returned will be 0, therefore changed to -1.

// Todo: make stuff have different actions when blown up
DESTROYED_BLOW_UP = 1
DESTROYED_TRANSPARENT = 2

function GM:PropTakeDamage( ent, info )	
	local inflictor = info:GetInflictor()
	local attacker = info:GetAttacker()

	// If it's not ignitable, don't let it take damage from flame.
	if ( IsValid(inflictor) && inflictor:GetClass() == "entityflame" && !ent.Ignitable ) then
		ent:Extinguish()
		return
	end
	
	if ( self:IsBuild() ) then return end // Don't take damage in build.
	if ( (IsValid(inflictor) && inflictor:IsPlayer()) || (IsValid(attacker) && attacker:IsPlayer()) ) then return end // Don't get hurt by players.
	if ( !ent.ShouldTakeDamage ) then return end // Don't hurt what shouldn't be hurt. :o

	// DAMAGE RAWR
	self:SetPropHealth( ent, self:GetPropHealth( ent ) - info:GetDamage(), !ent.BlowUp )
end
GM:AddHook( "EntityTakeDamage", "PropTakeDamage" )

function GM:GetPropHealth( prop )
	return prop:GetNWInt("hp") - 1
end
function GM:SetPropHealth(prop, health, noeffects)	
	prop:SetNWInt("hp", math.max(health, 0) + 1)
	
	if ( !noeffects ) then
		local healthPercent = self:GetPropHealthPercent( prop )
		local a = 20 + (healthPercent * healthPercent * 235)
		prop:SetColor( Color( a, a, a, 255 ) )
	
		// If our health has reached 0, explode!
		if ( health <= 0 && !prop.Exploded ) then
			local explode = ents.Create( "env_explosion" )
				explode:SetPos( prop:LocalToWorld( prop:OBBCenter() ) )
			explode:Spawn()
			explode:Fire( "Explode", "", 0 )
		
			prop.Exploded = true
		
			timer.Simple(3, function()
				if IsValid(prop) then prop:Remove() end
			end)
		end
	end
end

function GM:GetPropMaxHealth( prop )
	return prop:GetNWInt("maxhp") - 1
end
function GM:SetPropMaxHealth( prop, max )
	prop:SetNWInt("maxhp", math.max( max, 0 ) + 1)
	self:SetPropHealth(prop, self:GetPropHealth(prop)) // Slightly hacky way of getting colour to refresh.
end

function GM:GetPropHealthPercent( prop )
	if ( self:GetPropHealth( prop ) == 0 ) then return 0 end
	return math.Clamp( self:GetPropHealth( prop ) / self:GetPropMaxHealth( prop ), 0, 1 )
end

local Entity = FindMetaTable( "Entity" )
if ( !Entity ) then return end

function Entity:GetPropHealth()
	return GAMEMODE:GetPropHealth( self )
end
function Entity:SetPropHealth( amount, noeffects )
	GAMEMODE:SetPropHealth( self, amount, noeffects )
end
function Entity:GetPropMaxHealth()
	return GAMEMODE:GetPropMaxHealth( self )
end
function Entity:SetPropMaxHealth( amount )
	GAMEMODE:SetPropMaxHealth( self, amount )
end